import React, { useMemo } from 'react';
import { Modal, Form, Input, Select, Row, Col, TreeSelect, Upload, Button } from 'antd';
import { OrganizationItem, TemplateItem } from 'admin/schema/Cas';
import { useSelector } from 'react-redux';
import { convertToTree, downLoadByUrl } from '../utils';
import { uploadUrl } from 'admin/servers/servers';
import { find, get, includes } from 'lodash';
import { UploadOutlined } from '@ant-design/icons';

interface Props {
  visible: boolean;
  title: string;
  onOk: () => void;
  onCancel: () => void;
  editingTemplate: TemplateItem | null;
  organizations: Omit<OrganizationItem, 'children' | 'description'>[];
  signatures: any[];
  form: any;
}

const TemplateFormModal: React.FC<Props> = ({
  visible,
  title,
  onOk,
  onCancel,
  editingTemplate,
  organizations,
  signatures,
  form,
}) => {
  const uniqueToken = useSelector((state: any) => state.uniqueToken);
  const userInfo = useSelector((state: any) => state.loginInfo);

  // 使用 useMemo 缓存树形数据转换结果，避免不必要的重复计算
  const treeData = useMemo(() => {
    const treeData = convertToTree(organizations);
    return treeData;
  }, [organizations]);

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
      destroyOnClose
    >
      <Form form={form} layout="vertical">
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              name="name"
              label="名称"
              rules={[
                { required: true, message: '请输入名称' },
                { max: 20, message: '最大长度为20位字符' },
              ]}
            >
              <Input placeholder="请输入名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="type" label="类型" rules={[{ required: true, message: '请选择类型' }]}>
              <Select mode="multiple" placeholder="请选择类型" disabled={!!editingTemplate}>
                <Select.Option value="行业短信">行业短信</Select.Option>
                <Select.Option value="靶向短信">靶向短信</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              name="organizationId"
              label="单位"
              rules={[{ required: true, message: '请选择单位' }]}
            >
              <TreeSelect
                showSearch
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择单位"
                allowClear
                treeDefaultExpandAll
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                treeData={treeData}
                treeNodeFilterProp="title"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="signatureId"
              label="签名"
              rules={[{ required: true, message: '请选择签名' }]}
            >
              <Select placeholder="请选择签名">
                {signatures.map(signature => (
                  <Select.Option key={signature.id} value={signature.id}>
                    {signature.name}
                    <span style={{ color: '#c3c3c3' }}>（{signature.type}）</span>
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              rules={[
                { required: true, message: '请输入内容' },
                { max: 500, message: '最大长度为500位字符' },
              ]}
              name="content"
              label="内容"
            >
              <Input.TextArea placeholder="请输入内容" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              style={{ marginBottom: 0 }}
              shouldUpdate={(prevValues, currentValues) =>
                prevValues.organizationId !== currentValues.organizationId ||
                prevValues.type !== currentValues.type
              }
            >
              {() => {
                const target = find(organizations, { id: form.getFieldValue('organizationId') });
                if (includes(form.getFieldValue('type'), '靶向短信') && target) {
                  return (
                    <Form.Item
                      name="ctFileUrl"
                      label="中国电信授权委托函"
                      rules={[{ required: true, message: '请上传中国电信授权委托函' }]}
                      valuePropName="fileList"
                      getValueFromEvent={e => {
                        if (Array.isArray(e)) {
                          return e;
                        }
                        return e && e.fileList;
                      }}
                      extra={
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          {target?.emergency === 1 && (
                            <a href="/webapp/模板-中国电信授权委托函-应急类.docx" target="_blank">
                              模板-中国电信授权委托函-应急类.docx
                            </a>
                          )}
                          {target?.emergency === 0 && (
                            <a href="/webapp/模板-中国电信授权委托函-非应急类.docx" target="_blank">
                              模板-中国电信授权委托函-非应急类.docx
                            </a>
                          )}
                        </div>
                      }
                    >
                      <Upload
                        name="files"
                        action={uploadUrl}
                        headers={{
                          uniqueToken,
                          userId: userInfo.id,
                        }}
                        showUploadList={{
                          showPreviewIcon: false,
                          showDownloadIcon: true,
                        }}
                        onDownload={(file: any) => {
                          downLoadByUrl(
                            get(file, 'response.data[0].path'),
                            get(file, 'response.data[0].realName')
                          );
                        }}
                      >
                        <Button icon={<UploadOutlined />}>上传中国电信授权委托函</Button>
                      </Upload>
                    </Form.Item>
                  );
                }
              }}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              style={{ marginBottom: 0 }}
              shouldUpdate={(prevValues, currentValues) =>
                prevValues.organizationId !== currentValues.organizationId ||
                prevValues.type !== currentValues.type
              }
            >
              {() => {
                const target = find(organizations, { id: form.getFieldValue('organizationId') });
                if (includes(form.getFieldValue('type'), '靶向短信') && target) {
                  return (
                    <Form.Item
                      dependencies={['organizationId', 'type']}
                      rules={[{ required: true, message: '请上传中国联通授权委托函' }]}
                      name="cuFileUrl"
                      label="中国联通授权委托函"
                      valuePropName="fileList"
                      getValueFromEvent={e => {
                        if (Array.isArray(e)) {
                          return e;
                        }
                        return e && e.fileList;
                      }}
                      extra={
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          {target?.emergency === 1 && (
                            <a href="/webapp/模版-中国联通授权委托函-应急类.docx" target="_blank">
                              模版-中国联通授权委托函-应急类.docx
                            </a>
                          )}
                          {target?.emergency === 0 && (
                            <a href="/webapp/模版-中国联通授权委托函-非应急类.docx" target="_blank">
                              模版-中国联通授权委托函-非应急类.docx
                            </a>
                          )}
                        </div>
                      }
                    >
                      <Upload
                        name="files"
                        action={uploadUrl}
                        headers={{
                          uniqueToken,
                          userId: userInfo.id,
                        }}
                        showUploadList={{
                          showPreviewIcon: false,
                          showDownloadIcon: true,
                        }}
                        onDownload={(file: any) => {
                          downLoadByUrl(
                            get(file, 'response.data[0].path'),
                            get(file, 'response.data[0].realName')
                          );
                        }}
                      >
                        <Button icon={<UploadOutlined />}>上传中国联通授权委托函</Button>
                      </Upload>
                    </Form.Item>
                  );
                }
              }}
            </Form.Item>
          </Col>
        </Row>
        <p>
          注意：
          <br />
          {`1.模板参数若定义为{xxx}形式，xxx为参数名称，参数名称只能包含数字或大小写字母，变量最多5个，参数长度最大支持20个字符。`}
          <br />
          2.短信长度（签名+正文）不超过70字时，按照1条短信计费；超过70字即为长短信时，按67字/条分隔成多条计费。
          <br />
          例如，短信长度为80字，则按照67字/13字/分隔成2条计费，但短信接收方收到的是完整短信而非2条分开的短信。
          <br />
          3.短信模板内容不能含有【】符号。
          <br />
          4.单条短信内容不能超过500个字符。
          <br />
          <strong>
            示例：
            <br />
            {`尊敬的用户,您在本平台的验证码为{xxx},如非本人请勿操作,{xxxx}分钟内有效.`}
          </strong>
        </p>
      </Form>
    </Modal>
  );
};

// 使用 React.memo 优化组件性能，避免不必要的重渲染
export default React.memo(TemplateFormModal);
